package com.xstablet.activity.web;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.NormalDialog;
import com.lib.ui.activity.web.base.BaseBusinessWebActivity;
import com.lib.view.navigationbar.NomalNavigationBar;
import com.tencent.smtt.sdk.WebView;
import com.xstablet.R;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 陪伴课
 */

@Route(path = ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
public class NormalDetailWebActivity extends BaseBusinessWebActivity {

    private TextView title;

    private String urlPath;

    private WebView webView;

    private NomalNavigationBar navigationBar;

    private String webviewImageUrl;

    DialogUtils dialogUtils;

    @Override
    protected void onCreateView(WebView webView) {

        super.onCreateView(webView);
        this.webView = webView;

        urlPath = getIntent().getStringExtra("urlPath");
        initWebView(webView);

        if ("".equals(urlPath) || null == urlPath) {

            LogUtil.e("======>无效的地址");
            return;
        }

        webView.loadUrl(urlPath);

        dialogUtils = new DialogUtils();

        initView();

        //当webview中有图片并且需要保存的，提示用户长按图片可保存
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
                // 如果是图片类型或者是带有图片链接的类型
                if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                        hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

                    // 弹出保存图片的对话框
                    CoachAIStudyDialog.getInstance().setTitle("温馨提示").setContent("保存图片到本地")
                            .setSureListener(new CoachAIStudyDialog.SurelListener() {
                                @Override
                                public void onSure() {
                                    webviewImageUrl = hitTestResult.getExtra();//获取图片链接
                                    //保存图片到相册
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            url2bitmap(webviewImageUrl);
                                        }
                                    }).start();
                                }
                            }).show(getSupportFragmentManager());

                    return true;
                }

                return false;//保持长按可以复制文字
            }
        });

    }

    private void initWebView(WebView webView) {

    }

    private void initView() {

        //商城网页需要H5来设置title
        if (StringUtil.isNotEmpty(urlPath, true)) {

            //如果地址包含flat.html#/mall，则表示是商城地址，不设置title
            if (urlPath.contains("flat.html#/mall")) {

            } else {
                initTitle();
            }
        }

    }

    private TextView close;

    protected void initTitle() {

        navigationBar = new
                NomalNavigationBar.Builder(this)
                .setTitle("")
                .setRightIcon(R.mipmap.nav_share)
                .setLeftText("关闭")
                .setLeftTextClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        finish();
                    }
                })
                .setRightClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        toShare();
                        showToast("目前不能分享哦！");
                    }
                })
                .setLeftClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String str = "welfare";
                        if (webView != null) {

                            if (!"".equals(webView.getUrl()) && !"null".equals(webView.getUrl())) {
                                String currentUrl = webView.getUrl();
                                if (currentUrl.contains(str)) {

                                    webView.loadUrl("javascript:exitPage()");

                                } else {
                                    if (webView.canGoBack()) {
                                        webView.goBack();

                                    } else {
                                        finish();

                                    }
                                }
                            } else {
                                finish();
                            }
                        } else {
                            finish();
                        }

//                        if (webView.canGoBack()) {
//                            webView.goBack();
//
//                        } else {
//                            finish();
//
//                        }
                    }
                }).builder();


        title = navigationBar.getTitleTextView();
        close = (TextView) navigationBar.getView(R.id.left_text);

        close.setVisibility(View.GONE);
    }


    @Override
    protected int getWebLayoutId() {
        return R.layout.activity_company_class;
    }

    @Override
    protected void myOnPageStarted(WebView webView, String s, Bitmap bitmap) {

        dialogUtils.showNormalDialog(this, "页面加载中......");
    }

    @Override
    protected void myShouldOverrideUrlLoading(WebView webView, String url) {

    }

    @Override
    protected void myOnPageFinished(WebView webView, String s) {

        dialogUtils.dismiss();

        if (!StringUtil.isNotEmpty(webView.getUrl(), true)) {

            return;
        } else {

            String nowUrl = webView.getUrl();//获取当前地址

            if (nowUrl.contains("flat.html#/mall")) {

            } else {

                title.setText(webView.getTitle());

                if (webView.canGoBack()) {
                    close.setVisibility(View.VISIBLE);
                }

                if (nowUrl.contains("teacherHome_topic.html")) {//判断是否老师话题详情界面

                    if (nowUrl.contains("is_self")) {//如果包含is_self,表示老师可以分享自己

                    } else {

                        navigationBar.getView(R.id.right_icon).setVisibility(View.GONE);

                    }

                }
            }
        }

    }

    //把url转换为bitmap对象（要在子线程操作）
    public void url2bitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            int length = http.getContentLength();
            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            if (bm != null) {
                save2Album(bm);
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToast("保存失败");
                }
            });
            e.printStackTrace();
        }
    }

    //保存照片到相册，并通知系统更新相册
    private void save2Album(Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "xuesituimage");
        if (!appDir.exists()) appDir.mkdir();
        String[] str = webviewImageUrl.split("/");
        String fileName = str[str.length - 1];
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            onSaveSuccess(file);
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showToast("保存失败");
                }
            });
            e.printStackTrace();
        }
    }

    private void onSaveSuccess(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                showToast("保存成功");
            }
        });
    }


}
